package com.ruoyi.system.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.mapper.SysOrderMapper;
import com.ruoyi.system.service.ISysOrderService;
import com.ruoyi.common.core.domain.entity.SysOrder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;

/**
 * 订单信息服务层实现
 *
 * @author Kelsey
 */
@Service
public class SysOrderServiceImpl implements ISysOrderService {

    @Autowired
    private SysOrderMapper sysOrderMapper;

    /**
     * 查询订单列表
     * @param order 条件查询
     * @return 订单列表
     */
    @Override
    public List<SysOrder> selectOrderList(SysOrder order) {
        return sysOrderMapper.selectOrderList(order);
    }

    /**
     * 新增订单
     * @param order 订单
     * @return 结果
     */
    @Override
    public int insertOrder(SysOrder order) {
        return sysOrderMapper.insertOrder(order);
    }

    /**
     * 修改订单
     * @param order 订单
     * @return 结果
     */
    @Override
    public int updateOrder(SysOrder order) {
        return sysOrderMapper.updateOrder(order);
    }

    /**
     * 批量删除订单
     * @param orderIds 订单ID数组
     * @return 结果
     */
    @Override
    public int deleteOrderByIds(Long[] orderIds) {
        for (Long orderId : orderIds) {
            SysOrder order = sysOrderMapper.selectOrderById(orderId);
            if (StringUtils.isNotNull(order) && "2".equals(order.getDelFlag())) {
                throw new ServiceException(String.format("订单ID %1$s 已删除，无法删除", orderId));
            }
        }
        return sysOrderMapper.deleteOrderByIds(orderIds);
    }

    /**
     * 根据订单号查询订单
     * @param orderNo 订单号
     * @return 订单
     */
    @Override
    public SysOrder selectOrderByNo(String orderNo) {
        return sysOrderMapper.selectOrderByNo(orderNo);
    }

    /**
     * 校验订单是否存在
     * @param order 订单
     * @return 结果
     */
    @Override
    public boolean checkOrderExist(SysOrder order) {
        Long orderId = StringUtils.isNull(order.getOrderId()) ? -1L : order.getOrderId();
        SysOrder info = sysOrderMapper.selectOrderByNo(order.getOrderNo());
        if (StringUtils.isNotNull(info) && info.getOrderId().longValue() != orderId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }
}